<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import Table from '@/components/Form/table'
import { getInformationListAPI, addInformationAPI, getInformationInfoAPI, editInformationAPI, delInformationAPI } from '@/api/informationManagement'
import Pagination from '@/components/Form/Pagination'
import uploadImg from '@/components/ImageUpload/uploadImg'
import ImagePreview from '@/components/ImagePreview'
import { useCateList, useArticleStatus } from '@/hooks/index.js'
import Editor from '@/components/Form/Editor'
import { ElMessage } from 'element-plus';

const cateList = useCateList()
const articleStatus = useArticleStatus()

const state = (val) => articleStatus.find(item => item.value === val).label
// 表单查询数据
const queryData = reactive({
  current: 1,
  pageSize: 6,
  create_time: '',
  title: '',
  cate_id: '',
  status: ''
})
// 渲染列表
const list = ref([])
const total = ref(0)
const initData = async () => {
  // 发送请求
  const { data: { count, rows } } = await getInformationListAPI(queryData)
  console.log({ data: { count, rows } })
  // 赋值
  list.value = rows.map(({ pic_url, ...item }) => ({ pic_url: import.meta.env.VITE_APP_BASE_IMG + (pic_url ? pic_url.split(',')[0] : '/public/dist/static/empty.1e2fbc24.png'), ...item }))
  total.value = count
}
onMounted(() => {
  initData()
})
const informationTable = [
  { value: 'id', label: 'ID' },
  { value: 'title', label: '文章标题' },
  { value: 'article_cate.catename', label: '分类名' },
  { value: 'pic_url', label: '封面图' },
  { value: 'status', label: '状态' },
  { value: 'create_time', label: '创建时间' }
]
// 查询
const onSearch = () => {
  // queryData.pageNum=1
  queryData.create_time = queryData.create_time !== '' ? queryData.create_time.map(item => +item).join(',') : queryData.create_time
  initData()
}
// 重置
const onReset = () => {
  Object.assign(queryData, {
    current: 1,
    pageSize: 6,
    create_time: '',
    title: '',
    cate_id: '',
    status: '',

  })
  initData()
}
// 抽屉开关控制变量
const drawer = ref(false)
// 表单数据
const formData = reactive({
  title: '',
  cate_id: '',
  pic_url: '',
  status: '',
  content: ''
})
// 表单校验
const formRules = {
  title: [{ required: true, message: "请输入", trigger: "blur" }],
  cate_id: [{ required: true, message: "请选择", trigger: "change" }],
  content: [{ required: true, message: "请输入", trigger: "blur" }]
}
// 表单引用
const formRef = ref()
// 标题事件
const title = computed(() => {
  return formData.id ? '修改资讯' : '新增资讯'
})
// 抽屉关闭之前
const handleClose = () => {
  // 移除校验
  formRef.value.resetFields()
  // 重置表单
  Object.assign(formData, {
    title: '',
    cate_id: '',
    pic_url: '',
    status: '',
    content: ''
  })
  drawer.value = false
}
// 富文本
const changeInput = (val) => {
  // console.log(val);
  formData.content = val
}
// 表单提交
const onSubmit = async () => {
  try {
    // 表单校验
    await formRef.value.validate()
    // 处理数据
    const data = toRaw(formData)
    // 发送请求
    formData.id ? await editInformationAPI(data) : await addInformationAPI(data)
    // 提示成功
    ElMessage.success('操作成功')
    // 关闭弹框
    drawer.value = false
    // 移除校验
    await formRef.value.resetFields()
    // 更新列表
    initData()
  } catch (error) {
    console.log(error)
  }
}
// 修改数据回显
const replyData = async (id) => {
  // 发送请求
  let { data } = await getInformationInfoAPI(id)
  // console.log(data)
  Object.assign(formData, data)
  drawer.value = true
}
// 修改事件
const edit = (id) => {
  replyData(id)
}
// 删除事件
const del = async (id) => {
  // 发送请求
  await delInformationAPI(id)
  // 提示成功
  ElMessage.success('删除成功')
  // 边缘问题
  if (queryData.pageNum > 1 && list.value.length === 1) queryData.pageNum--
  initData()
}
</script>

<template>
  <div>
    <el-card>
      <b>资讯管理</b> <b style="font-weight: 400;font-size:12px;">用于一些党建宣传，社区知识等相关文章信息的编辑发布</b>
      <el-card>
        <!-- 搜索区域 -->
        <el-form label-width="70px" :inline="true" size="normal">
          <el-row :gutter="20">
            <el-col :span="5" :offset="0">
              <el-form-item label="文章标题">
                <el-input placeholder="请输入" v-model="queryData.title"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="5" :offset="0">
              <el-form-item label="分类名">
                <el-select placeholder="请输入" v-model="queryData.cate_id">
                  <el-option v-for="item in cateList" :key="item.id" :label="item.catename" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="5" :offset="0">
              <el-form-item label="状态">
                <el-select placeholder="请输入" v-model="queryData.status">
                  <el-option v-for="item in articleStatus" :key="item.id" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="9" :offset="0">
              <el-form-item label="创建时间">
                <el-date-picker v-model="queryData.create_time" type="daterange" range-separator="至"
                  start-placeholder="开始日期" end-placeholder="结束日期" style="width:250px">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="19"></el-col>
            <el-col :span="5" :offset="0">
              <el-form-item>
                <el-button type="primary" @click="onSearch">查询</el-button>
                <el-button @click="onReset">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <br>

      <el-card>
        <!-- 工具区域 -->
        <el-row type="flex" justify="space-between">
          <div></div>
          <div>
            <el-button type="primary" @click="drawer = true">新增资讯</el-button>
          </div>
        </el-row>
        <br>

        <!-- 表格区域 -->
        <Table :table="informationTable" :tableData="list" @del="del" @edit="edit">
          <template #article_cate.catename="{ row }">{{ row.article_cate?.catename }}</template>
          <template #pic_url="{ row }">
            <div style="width:100%">
              <ImagePreview :src="row.pic_url" alt="" :width="50"></ImagePreview>
            </div>
          </template>
          <template #status="{ row }">{{ state(row.status) }}</template>
          <template #create_time="{ row }">{{ new Date(row.create_time).toLocaleString() }}</template>
        </Table>

        <!-- 分页区域 -->
        <Pagination v-model:pageNum="queryData.current" v-model:pageSize="queryData.pageSize" :total="total"
          @initData="initData" />

        <!-- 新增、修改抽屉 -->
        <el-drawer size="50%" v-model="drawer" direction="rtl" :title="title" :before-close="handleClose">
          <el-form :model="formData" ref="formRef" :rules="formRules" label-width="120px" :inline="false" size="normal">

            <el-form-item label="文章标题" prop="title">
              <el-input v-model="formData.title" style="width: 50%" placeholder="请输入"></el-input>
            </el-form-item>

            <el-form-item label="文章分类" prop="cate_id">
              <el-select placeholder="请选择" v-model="formData.cate_id" style="width: 50%">
                <el-option v-for="item in cateList" :key="item.id" :label="item.catename" :value="item.id"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="文章状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio v-for="item in articleStatus" :key="item.id" :label="item.value" size="large">{{ item.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="文章封面" prop="pic_url">
              <uploadImg v-model:imgUrl="formData.pic_url" :limit="3" />
            </el-form-item>

            <el-form-item label="文章内容" prop="content">
              <!-- 富文本组件 -->
              <Editor :value="formData.content" :min-height="192" @update:input="changeInput" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="onSubmit">确定</el-button>
              <el-button @click="handleClose">取消</el-button>
            </el-form-item>

          </el-form>

        </el-drawer>

      </el-card>
    </el-card>

  </div>
</template>
<style></style>

